package com.sfc.spiderweb.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sfc.spiderweb.entity.LazadaUser;
import com.sfc.spiderweb.mapper.LazadaUserMapper;
import com.sfc.spiderweb.service.LazadaUserService;
import com.sfc.spiderweb.util.DateUtil;
import com.sfc.spiderweb.util.ExcelUtils;
import com.sfc.spiderweb.util.FTPUtil;
import com.sfc.spiderweb.util.HttpClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 李振伟(Earl Li)
 * @title: LazadaUserServiceImpl
 * @projectName spider-web
 * @description: ${description}
 * @date 2020/1/1011:55
 */
@Slf4j
@Service
public class LazadaUserServiceImpl extends ServiceImpl<LazadaUserMapper, LazadaUser> implements LazadaUserService {

    @Value("${ftp.url}")
    private String ftpUrl;
    @Value("${ftp.port}")
    private Integer ftpPort;
    @Value("${ftp.user}")
    private String ftpUser;
    @Value("${ftp.password}")
    private String ftpPassword;
    @Value("${mail.sender}")
    private String mailSender;
    @Value("${mail.password}")
    private String mailPassword;
    @Value("${mail.finance-lazada-performance}")
    private String mailFinanceLazadaPerformance;
    @Value("${mail.send-emil-url}")
    private  String emailUrl;

    @Override
    public void lazadaPerformance() {
        List<List<String>> lazadaPerformanceList = new ArrayList<>();
        List<String> topList = Arrays.asList("账号", "是否有数据");
        lazadaPerformanceList.add(topList);
        String dateStr = DateUtil.getNetTime();
        //初始化时间
        Date date = DateUtil.parse(dateStr, "yyyy-MM-dd");
        String thisWeekTHURSDAY = DateUtil.getThisWeekTHURSDAY(date);
        FTPClient ftp = FTPUtil.getFTPClient(ftpUrl, ftpPort, ftpUser, ftpPassword);
        final String ftpPath = "/financeFtp/lazada_performance/";
        //final String outPath = "D:\\财务\\lazada周表现\\" + thisWeekTHURSDAY + "check.xlsx";
        final String outPath = "\\check.xlsx";
        List<LazadaUser> lazadaUserList = this.list();
        if (CollectionUtils.isEmpty(lazadaUserList)) {
            return;
        }
        List<FTPUtil.FilePath> filePathList = FTPUtil.getFilePath(ftp, ftpPath + thisWeekTHURSDAY);
        List<String> ftpFileName = filePathList.stream().map(FTPUtil.FilePath::getName).collect(Collectors.toList());
        for (LazadaUser lazadaUser : lazadaUserList) {
            String fileName = lazadaUser.getPlatformCode() + "_" + thisWeekTHURSDAY + ".txt";
            if (ftpFileName.contains(fileName)) {
                lazadaPerformanceList.add(Arrays.asList(lazadaUser.getPlatformCode(), "是"));
            } else {
                lazadaPerformanceList.add(Arrays.asList(lazadaUser.getPlatformCode(), "否"));
            }
        }
        try {
            byte[] lazadaPerformances = ExcelUtils.writeExcel1(outPath, Arrays.asList("lazadaPerformance"), Arrays.asList(lazadaPerformanceList));
            sendMail(thisWeekTHURSDAY, lazadaPerformances);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public void sendMail(String date, byte[] lazadaPerformances) {
        Map<String, Object> otherParam = new HashMap<>();
        // 发送人邮箱
        otherParam.put("emailUsername", mailSender);
        //抄送
        //otherParam.put("ccList", mailFinance1);
        // 邮箱密码
        otherParam.put("emailPassword", mailPassword);
        otherParam.put("sender", date + "lazada周表现数据");
        otherParam.put("subject", "Earl");
        otherParam.put("content", date + "lazada周表现数据");
        // 接收人邮箱
        otherParam.put("receiveList", String.join(",", Arrays.asList(mailFinanceLazadaPerformance.split(","))));
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        // 设置文件名称
        map.put("name", "lazadaPerformance-check+" + date + ".xlsx");
        // 设置文件base64
        map.put("base64", Base64.getEncoder().encodeToString(lazadaPerformances));
        list.add(map);
        otherParam.put("fileList", list);
        Object param = JSONObject.toJSON(otherParam);
        log.info("调用邮件接口:{}", param);
        String mailResult = HttpClient.doPost(emailUrl, param.toString(), "POST");
        log.info("返回邮件接口:{}", mailResult);
    }


}
